const db = require('../config/database');

class Region {
    static async create(regionData) {
        try {
            const [result] = await db.query(
                'INSERT INTO regions (name, code, level, status, parent_id, manager_id) VALUES (?, ?, ?, ?, ?, ?)',
                [
                    regionData.name,
                    regionData.code,
                    regionData.level,
                    regionData.status || 'active',
                    regionData.parent_id || null,
                    regionData.manager_id || null
                ]
            );
            return result.insertId;
        } catch (error) {
            console.error('创建区域失败:', error);
            throw error;
        }
    }

    static async findById(id) {
        try {
            const [rows] = await db.query(
                'SELECT * FROM regions WHERE id = ?',
                [id]
            );
            return rows[0];
        } catch (error) {
            console.error('查询区域失败:', error);
            throw error;
        }
    }

    static async findAll() {
        try {
            const [rows] = await db.query('SELECT * FROM regions');
            return rows;
        } catch (error) {
            console.error('查询所有区域失败:', error);
            throw error;
        }
    }

    static async update(id, regionData) {
        try {
            const { name, code, level, parent_id = null, status = 'active', manager_id = null } = regionData;
            
            const [result] = await db.query(
                'UPDATE regions SET name = ?, code = ?, level = ?, parent_id = ?, status = ?, manager_id = ? WHERE id = ?',
                [name, code, level, parent_id, status, manager_id, id]
            );
            
            return result.affectedRows > 0;
        } catch (error) {
            console.error('更新区域失败:', error);
            throw error;
        }
    }

    static async delete(id) {
        try {
            const [result] = await db.query('DELETE FROM regions WHERE id = ?', [id]);
            return result.affectedRows > 0;
        } catch (error) {
            console.error('删除区域失败:', error);
            throw error;
        }
    }

    static async setManager(id, managerId) {
        try {
            const [result] = await db.query(
                'UPDATE regions SET manager_id = ? WHERE id = ?',
                [managerId, id]
            );
            return result.affectedRows > 0;
        } catch (error) {
            console.error('设置区域负责人失败:', error);
            throw error;
        }
    }

    static async findByCode(code) {
        try {
            const [rows] = await db.query(
                'SELECT * FROM regions WHERE code = ?',
                [code]
            );
            return rows[0] || null;
        } catch (error) {
            console.error('查询区域编码失败:', error);
            throw error;
        }
    }

    static hasChildren(id, callback) {
        db.query('SELECT COUNT(*) as count FROM regions WHERE parent_id = ?', [id], (err, rows) => {
            if (err) return callback(err);
            callback(null, rows[0].count > 0);
        });
    }

    static async checkCodeExists(code, excludeId = null) {
        try {
            let query = 'SELECT * FROM regions WHERE code = ?';
            const params = [code];
            
            if (excludeId) {
                query += ' AND id != ?';
                params.push(excludeId);
            }
            
            const [rows] = await db.query(query, params);
            return rows.length > 0;
        } catch (error) {
            console.error('检查区域编码失败:', error);
            throw error;
        }
    }
}

module.exports = Region; 